package com.dindang.propertyfee.mvp.presenter;

import android.app.Application;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.dindang.propertyfee.app.AppConst;
import com.dindang.propertyfee.app.utils.print.AidlUtil;
import com.dindang.propertyfee.mvp.contract.QrCodeCollectionContract;
import com.dindang.propertyfee.mvp.model.api.PropertyfeeApi;
import com.dindang.propertyfee.mvp.model.entity.BaseResponse;
import com.dindang.propertyfee.mvp.model.entity.PayEventMessage;
import com.dindang.propertyfee.mvp.model.entity.PropertyCharge;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.utils.TextViewUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class QrCodeCollectionPresenter extends BasePresenter<QrCodeCollectionContract.Model, QrCodeCollectionContract.View>{
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private Bitmap mBitmap;
    private int countDown5 = 5;
    private String billMoney;
    private StringBuffer content;
    private PropertyCharge.RecordDetail mRecordDetail;
    private String[] mCollectionType = {"", "现金", "POS", "微信", "支付宝", "银行转账"};
    private PropertyCharge.GetDetailPara mParamdetail = new PropertyCharge.GetDetailPara();
    private List<PropertyCharge.RecordDetail> mRecordDetailList = new ArrayList<>();


    @Inject
    public QrCodeCollectionPresenter(QrCodeCollectionContract.Model model, QrCodeCollectionContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        EventBus.getDefault().register(this);
        mRootView.getGroupQrCode().setVisibility(View.VISIBLE);
        initQrCode();
        mRootView.getTvPrint().setOnClickListener(v -> {
            getDetail();
        });
    }
//点击打印
//    private void clickPrint(){
////        PropertyCharge.Record4Client.FeeList feeList = mList.get(position);
//        ARouter.getInstance().build("/propertyfee/activity/PrintActivity")
//                .withString(AppConst.ID, "0")
//                .navigation();
//
//    }

    //获取账单详情
    private void getDetail() {
        mParamdetail.id= mRootView.getActivity().getIntent().getStringExtra(AppConst.ID);
        //假数据
//        mParamCash.id = "177";
        mModel.getDetail(mParamdetail)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {

                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse<List<PropertyCharge.RecordDetail>>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse<List<PropertyCharge.RecordDetail>> response) {
                        if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                            MyApplication.getInstance().gotoLoginActivity();
                        }
                        if(!response.isSuccess()){
                            ArmsUtils.makeText(mApplication, response.getStatuMsg());
                            return;
                        }

                        mRecordDetailList.addAll(response.getData());

                        if (null != mRecordDetailList && mRecordDetailList.size() > 0) {
                            mRecordDetail = mRecordDetailList.get(0);
                            print();//开始打印
                        }

                    }
                });
    }

    public void print() {
        if(Build.MODEL.equals("V1s")){
            setPrintUiV1s();//设置打印数据
//            AidlUtil.getInstance().connectPrinterService(mRootView.getActivity());
            AidlUtil.getInstance().initPrinter();
            for (int i = 0; i <2 ; i++) {
                AidlUtil.getInstance().printText("\t\t\t\t\t\t\t\tXXX物业账单信息", 34, true, false);
                AidlUtil.getInstance().printText(content.toString()+"\n\n\n\n\n", 24, false, false);
            }
        }else if(Build.MODEL.equals("K-Link V6")){
            ArmsUtils.snackbarText("打印");
        }
    }

    private void setPrintUiV1s(){
        content = new StringBuffer();
        content.append("账单编号: " + mRecordDetail.c_payment_no);
        content.append("\n收款时间: " + mRecordDetail.d_receipt_date);
        content.append("\n住    址: " + mRecordDetail.addr);
        content.append("\n姓    名: " + mRecordDetail.c_payment_name);
        content.append("\n收 款 人: " + mRecordDetail.c_payee_name);
        content.append("\n收款方式: " + mCollectionType[mRecordDetail.c_collection_type]);
        content.append("\n-------------------------------");
        content.append("\n\t\t\t\t名称\t\t\t\t\t\t\t\t用量\t\t\t\t\t\t\t\t单价\t\t\t\t\t\t\t\t小计");
        content.append("\n\t\t\t\t"+mRecordDetail.c_fee_type_name+"\t\t\t\t\t\t\t\t"+mRecordDetail.c_quantity+"\t\t\t\t\t\t\t\t"+mRecordDetail.c_price+"\t\t\t\t\t\t\t\t"+mRecordDetail.countAmount);
        content.append("\n-------------------------------");
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void payRefresh(PayEventMessage payEventMessage){
        if(payEventMessage.getMessage()==1){
            mRootView.getGroupQrCode().setVisibility(View.GONE);
            mRootView.getGroupSuccess().setVisibility(View.VISIBLE);
            mRootView.getTvTitle().setText("支付成功");
            mRootView.getTvTotalPrice().setText(TextViewUtils.getPaymentSuccessPrice(mApplication, billMoney));
            mRootView.getTvPrint().setVisibility(View.VISIBLE);
        }else{
            mRootView.getGroupQrCode().setVisibility(View.GONE);
            mRootView.getGroupSuccess().setVisibility(View.VISIBLE);
            mRootView.getTvTitle().setText("支付失败");
            mRootView.getTvTotalPrice().setVisibility(View.INVISIBLE);
            mRootView.getTvPrint().setVisibility(View.INVISIBLE);
        }

    }

    private void initQrCode() {
        //获取手机deviceId
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        String deviceId = pushService.getDeviceId();
        String property_id = BaseAppConst.accountInfo.getHaiNaId();//海拉id
        LogUtils.debugInfo("zp","手机deviceId:::"+deviceId);
        String billIds = mRootView.getActivity().getIntent().getStringExtra(AppConst.RECEIVABLE_DETAIL_BILL_IDS);
        String billType = mRootView.getActivity().getIntent().getStringExtra(AppConst.RECEIVABLE_DETAIL_BILL_TYPE);
        billMoney = mRootView.getActivity().getIntent().getStringExtra(AppConst.RECEIVABLE_DETAIL_BILL_MONEY);
        String url = PropertyfeeApi.APP_PAY_HTML + "?billType=" + billType + "&billIds=" + billIds+ "&billMoney=" + billMoney+"&deviceId="+deviceId+"&property_id="+property_id;
        mBitmap = CodeUtils.createImage(url, 400, 400, null);
        mRootView.getIvQrCode().setImageBitmap(mBitmap);
        LogUtils.debugInfo("zp","url是：：：："+url);
//        mHandler.sendEmptyMessageDelayed(0, 5000);
        //收到阿里云推送，处理信息
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    mRootView.getGroupQrCode().setVisibility(View.GONE);
                    mRootView.getGroupSuccess().setVisibility(View.VISIBLE);
                    mRootView.getTvTitle().setText("支付成功");
                    mRootView.getTvTotalPrice().setText(TextViewUtils.getPaymentSuccessPrice(mApplication, billMoney));

                    mHandler.sendEmptyMessageDelayed(1, 1000);
                    break;
                case 1:
                    mRootView.getTvAutoJump().setText(TextViewUtils.getRedCountDown(mApplication, countDown5 + " 秒后自动跳转"));
                    if(countDown5 == 0){
                        mHandler.removeMessages(1);
                        mRootView.getActivity().finish();
                    }else{
                        countDown5--;
                        mHandler.sendEmptyMessageDelayed(1, 1000);
                    }
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        mHandler.removeMessages(0);
        mHandler.removeMessages(1);
        this.mBitmap = null;
        this.mHandler = null;
    }

}
